
const $api = require('../../api/index')

let QQMapWX = require('../../utils/qqmap-wx-jssdk.min.js')
let qqmapsdk = new QQMapWX({
	key: 'J3NBZ-556K3-U7Q3M-3TTNZ-FQYQT-YVFE2' // 必填
})
const moment = require('../../utils/moment');
import Dialog from '../../miniprogram_npm/@vant/weapp/dialog/dialog';

//创建内部 audio 上下文 InnerAudioContext 对象。
const innerAudioContext = wx.createInnerAudioContext()

const clockSuccessSrc = "https://files.anculsai.com/atten/clock_success.mp3"
const clockFailSrc = "https://files.anculsai.com/atten/clock_fail.mp3"
const noProjectSrc = "https://files.anculsai.com/atten/no_project.mp3"
const notChoosePrjSrc = "https://files.anculsai.com/atten/not_choose_prj.mp3"
const notChooseClocktypeSrc = "https://files.anculsai.com/atten/not_choose_clockType.mp3"
const notInrangeSrc = "https://files.anculsai.com/atten/not_inrange.mp3"

Page({

    /**
     * 页面的初始数据
     */
    data: {
        showPrjList: false,
        projectList: [],
        activePrj: {},
        isInRange: false, // 是否在考勤范围内
        devicePosition: "front", // front 前置，back后置
        clockType: "", // 1 进，0 出
        showLogin: false,
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        let userInfo = wx.getStorageSync('userInfo')
        if(userInfo.telnum){
            this.setData({
                userPhone: userInfo.telnum
            })
            this.getPrjByPhone()
        }
        this.setNavSize()
        this.getLocation()
        this.getNowDate()
        setInterval(() => {
            this.getLocation()
            this.getNowDate()
        }, 30000);
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {},

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        // 屏幕常亮
        wx.setKeepScreenOn({
            keepScreenOn: true
        })
        this.ctx = wx.createCameraContext() // 获取相机实例
    },

    /* 通过获取系统信息计算导航栏高度 */
    setNavSize: function () {
        var that = this,
            sysinfo = wx.getSystemInfoSync(),
            statusHeight = sysinfo.statusBarHeight,
            isiOS = sysinfo.system.indexOf('iOS') > -1,
            navHeight;
        if (!isiOS) {
            navHeight = 48;
        } else {
            navHeight = 40;
        }
        that.setData({
            statusHeight: statusHeight,
            navHeight: navHeight
        })
    },

    /* 获取当前时间 */
    getNowDate(){
        let nowTime = moment(new Date()).format('HH:mm') 
        let nowDate = moment(new Date()).format('YYYY-MM-DD') 
        let nowWeek = moment(new Date()).format('dddd')
        let zh_week = ""
        switch (nowWeek) {
            case "Monday":
                zh_week = "星期一"
                break;

            case "Tuesday":
                zh_week = "星期二"
                break;

            case "Wednesday":
                zh_week = "星期三"
                break;

            case "Thursday":
                zh_week = "星期四"
                break;

            case "Friday":
                zh_week = "星期五"
                break;

            case "Saturday":
                zh_week = "星期六"
                break;

            case "Sunday":
                zh_week = "星期日"
                break;
        
            default:
                break;
        }
        this.setData({
            nowTime,
            nowDate,
            zh_week
        })
    },

    /* 获取定位 */
    getLocation(){
		let that = this
		if (wx.getStorageSync('userLocation')) {
			// wx.showLoading({
			// 	title: "定位中",
			// 	mask: true,
			// })
			wx.getLocation({
				type: 'gcj02',
				isHighAccuracy: true, //高精度定位
				//定位成功，更新定位结果
				success: function (res) {
					let lat = res.latitude
					let lng = res.longitude
					that.setData({
						lat,
						lng,
					})
					qqmapsdk.reverseGeocoder({
						// 位置坐标，默认获取当前位置，非必须参数
						location: {
							latitude: lat,
							longitude: lng
						},
						success: function (qqRes) {
							let address = qqRes.result.address;//地址位置
							that.setData({
								address
							})
						},
						fail: function (error) {
							console.error('错误', error)
						}
					})
				},
				//定位失败回调
				fail: function () {
					wx.showToast({
						title: "定位失败",
						icon: "none"
					})
					wx.setStorageSync('userLocation', false)
				},

				complete: function () {
					//隐藏定位中信息进度
					// wx.hideLoading()
				}

			})
		} else {
			wx.openSetting({
				complete: (res) => {
					if (res.authSetting&&res.authSetting["scope.userLocation"]) {
						wx.setStorageSync('userLocation', true)
						that.getLocation()
					}
				}
			})
		}
	},

    //播放语音
    yuyinPlay(src) {
        if (src == '') {
            return;
        }
        innerAudioContext.autoplay = true
        innerAudioContext.src = src //设置音频地址
        innerAudioContext.play() //播放音频
    },
 
    // 结束语音
    endPlay(e) {
        innerAudioContext.stop()
    },

    /* 是否在考勤范围 */
    checkLocation(){
        let param = {
            deptId: this.data.activePrj.deptId,
            lng: this.data.lng,
            lat: this.data.lat
        }
        $api.gpsCheck(param).then(res=>{
            this.setData({
                isInRange: res.data
            })
        })
    },

    /* 获取项目 */
    getPrjByPhone(){
        let param = {
            phone: this.data.userPhone
        }
        $api.getProjectList(param).then(res=>{
            if(res.data.length===0){
                this.yuyinPlay(noProjectSrc)
                wx.showToast({
                    title: '您暂无考勤项目',
                    icon: 'error'
                })
                return
            }
            if(res.data.length===1){
                this.setData({
                    activePrj: res.data[0],
                    projectList: res.data,
                })
                let timerId = setInterval(() => {
                    if(this.data.lat){
                        clearInterval(timerId)
                        this.checkLocation()
                    }
                }, 1000)
            }else{
                this.setData({
                    projectList: res.data,
                    showPrjList: true
                })
            }
            
        })
    },

    /* 选择项目 */
    selectPrj(event){
        this.setData({
            activePrj: event.currentTarget.dataset.value,
            showPrjList: false
        })
        this.checkLocation()
    },

    /* 切换摄像头 */
    changePosition(){
        this.setData({
            devicePosition: this.data.devicePosition==="front"?"back":"front"
        })
    },

    /* 切换项目 */
    changePrj(){
        this.setData({
            showPrjList: true
        })
    },

    /* 切换进出场 */
    changeClock(e){
        let type = e.currentTarget.dataset.type
        this.setData({
            clockType: type
        })
    },

    /* 打卡 */
    handleClock() {
        if(!this.data.userPhone){
            // this.setData({
            //     showLogin: true
            // })
            Dialog.confirm({
                title: '提示',
                message: '未登录无法打卡, 是否登录继续?',
            })
            .then(() => {
                wx.redirectTo({
                    url: '/pages/login/login'
                })
            })
            .catch(() => {

            });
            return
        }

        let that = this
        
        if(!this.data.lat){
            wx.openSetting({
				complete: (res) => {
					if (res.authSetting&&res.authSetting["scope.userLocation"]) {
						wx.setStorageSync('userLocation', true)
						that.getLocation()
					}
				}
			})
            return
        }
        if(this.data.projectList.length===0){
            this.yuyinPlay(noProjectSrc)
            wx.showToast({
                title: '您暂无考勤项目',
                icon: 'error'
            })
            return
        }
        if(!this.data.activePrj.deptId){
            this.yuyinPlay(notChoosePrjSrc)
            wx.showToast({
                title: '请选择考勤项目',
                icon: 'error'
            })
            return
        }
        if(!this.data.isInRange){
            this.yuyinPlay(notInrangeSrc)
            wx.showToast({
                title: '不在考勤范围内',
                icon: 'error'
            })
            return
        }
        if(this.data.clockType===""){
            this.yuyinPlay(notChooseClocktypeSrc)
            wx.showToast({
                title: '请选择进出场',
                icon: 'error'
            })
            return
        }
        
		this.ctx.takePhoto({
			quality: 'high',
			success: (res) => {
				wx.getFileSystemManager().readFile({
					filePath: res.tempImagePath,
					encoding: 'base64',
					success(res) {
						let param = {
                            deptId: that.data.activePrj.deptId,
                            empId: that.data.activePrj.empId,
                            imageBase64: res.data,
                            direction: that.data.clockType,
                            lng: that.data.lng,
                            lat: that.data.lat
                        }
                        $api.faceAtten(param).then(res=>{
                            if(res.code=='200'){
                                that.yuyinPlay(clockSuccessSrc)
                                wx.showToast({
                                    title: "打卡成功",
                                    icon: 'success',
                                    duration: 2000
                                })
                            }else{
                                that.yuyinPlay(clockFailSrc)
                                wx.showToast({
                                    title: res.msg,
                                    icon: 'error',
                                    duration: 2000
                                })
                            }
                        }).catch(err=>{
                            that.yuyinPlay(clockFailSrc)
                            wx.showToast({
                                title: '人脸识别失败',
                                icon: 'error',
                                duration: 2000
                            })
                        })
					},
				})
			},
		})
	},

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {
        this.endPlay()
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {
        return {
            title: "安固士智慧工地考勤版",
            path: "/pages/index/index",
            imageUrl: "../../images/login_bg.png"
        }
    }
})
